package com.tjjingpan.study.aidlclient;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;

import com.tjjingpan.study.aidlservice.IServiceRemoteBindler;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,ServiceConnection{
    private Intent myServiceIntent;

    private EditText etInput;

    @SuppressLint({"MissingInflatedId", "LocalSuppress"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btnBindMyService).setOnClickListener(this);
        findViewById(R.id.btnUnbindMyService).setOnClickListener(this);
        findViewById(R.id.btnSync).setOnClickListener(this);

        etInput = findViewById(R.id.etInput);



        //显示启动另一个APP中的服务
        myServiceIntent = new Intent();
        myServiceIntent.setComponent(new ComponentName("com.tjjingpan.study.aidlservice","com.tjjingpan.study.aidlservice.MyService"));
    }

    @Override
    public void onClick(View view) {
        if(R.id.btn1 == view.getId()){
            startService(myServiceIntent);
        }
        if(R.id.btn2 == view.getId()){
            stopService(myServiceIntent);
        }

        if(R.id.btnBindMyService == view.getId()){
            bindService(myServiceIntent,this, Context.BIND_AUTO_CREATE);
        }
        if(R.id.btnUnbindMyService == view.getId()){
            unbindService(this);
        }

        if(R.id.btnSync == view.getId()){
            if(bindler!=null){
                try {
                    bindler.setData(etInput.getText().toString());
                } catch (RemoteException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        System.out.println("Bind Service");
        System.out.println(iBinder);

        bindler  =  IServiceRemoteBindler.Stub.asInterface(iBinder);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
    private IServiceRemoteBindler bindler = null;

}